package com.xxkj.drugtraceability.net

import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response

class BaseUrlInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        // 获取request
        val request = chain.request()
        // 从request中获取原有的HttpUrl实例oldHttpUrl
        val oldHttpUrl = request.url
        return if (WanService.BASE_URL.contains(oldHttpUrl.host) && WanService.BASE_URL.contains(oldHttpUrl.port.toString())) {
            chain.proceed(request)
        } else {
            // 获取request的创建者builder
            val newBuilder = request.newBuilder()
            val toHttpUrlOrNull = WanService.BASE_URL.toHttpUrlOrNull()
            val build: HttpUrl = oldHttpUrl.newBuilder().scheme(oldHttpUrl.scheme)
                    .host(toHttpUrlOrNull!!.host)
                    .port(toHttpUrlOrNull.port)
                    .build()
            chain.proceed(newBuilder.url(build).build())
        }
    }
}